package com.dap.core.config;

import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.Assert;

import com.dap.core.utils.IOUtils;
import com.dap.core.utils.StringUtils;

public class BootstrapConfigUtil {
    protected static final Logger LOGGER = LoggerFactory.getLogger(BootstrapConfigUtil.class);
    private static final String DEFAULT_BOOTSTRAP_PROPERTIES = "/config/bootstrap.properties";
    private static volatile Properties PROPERTIES;
    public static final String APP_NAME = "app.name";
    public static final String APP_VERSION = "app.version";
    public static final String APP_ENV = "app.env";
    public static final String APP_TENANTID = "app.tenantId";
    public static final String CONFIG_SERVER_HOST = "configsvr.host";
    public static final String CONFIG_SERVER_ENABLE = "configsvr.enable";
    public static final String LOAD_COMPONENTS = "components";

    static {
        synchronized (BootstrapConfigUtil.class) {
            if (PROPERTIES == null) {
                PROPERTIES = loadProperties(DEFAULT_BOOTSTRAP_PROPERTIES);
            }
        }
    }


    public static String getProperty(String key) {
        Assert.notNull(key, "the key must not be null ");

        String value = System.getenv(key);
        if ((value == null) || (value.trim().length() == 0)) {
            value = System.getProperty(key);
        }
        if ((value == null) || (value.trim().length() == 0)) {
            getProperties();
            value = PROPERTIES.getProperty(key);
        }
        value = StringUtils.replaceProperty(value, PROPERTIES);
        return value;
    }


    public static boolean isTrue(String key) {
        String value = getProperty(key);
        return "true".equalsIgnoreCase(value);
    }


    public static Properties getProperties() {
        return PROPERTIES;
    }


    private static Properties loadProperties(String fileName) {
        Properties properties;
        try {
            ClassPathResource resource = new ClassPathResource(fileName);
            properties = IOUtils.stream2props(resource.getInputStream());
        } catch (Exception e) {
            LOGGER.error("Failed to load bootstrap properties file from " + fileName, e);
            throw new ConfigException("Failed to load bootstrap properties file from " + fileName, e);
        }
        if (System.getenv(APP_NAME) != null) {
            System.setProperty(APP_NAME, System.getenv(APP_NAME));
        }
        if (System.getenv(APP_ENV) != null) {
            System.setProperty(APP_ENV, System.getenv(APP_ENV));
        }
        if (System.getenv(APP_VERSION) != null) {
            System.setProperty(APP_VERSION, System.getenv(APP_VERSION));
        }
        if (System.getenv(APP_TENANTID) != null) {
            System.setProperty(APP_TENANTID, System.getenv(APP_TENANTID));
        }
        return properties;
    }
}
